import React, { useEffect, useState, useRef } from 'react'
import { Button, Modal, Layout, Select, Cascader, Space, message, Table, Input, InputNumber, Popconfirm, Form, Typography, Row, Col } from 'antd';
import { EditTwoTone, DeleteTwoTone, ExclamationCircleOutlined } from '@ant-design/icons';
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
import { screenWidth } from '../../../Constants';
import axios from 'axios';
import myprovinceData from '../../../js/provinceData';
const { confirm } = Modal;
const { Option } = Select;
const { Search } = Input;
const provinceData = myprovinceData;
export default function Index() {
    let editUserInfo = {}
    let addUserInfo = {}
    const navigate = useNavigate()
    const [originData, setOriginData] = useState(0);
    const [goodList, setGoodList] = useState();
    const { Content, } = Layout;
    const [editvisible, seteditVisible] = useState(false);
    const [addvisible, setaddVisible] = useState(false);

    const [editGood, setEditGood] = useState('');
    const editGoodName = useRef();
    const editGoodPoint = useRef();

    const newGoodName = useRef();
    const newGoodPoint = useRef();

    useEffect(async () => {
        message.destroy();
        const resp = await axios.get("http://localhost:8080/qryGoods")
        setOriginData(resp.data.data)
        setGoodList(resp.data.data)
        return () => {

        };
    }, []);
    const deleteUser = (record) => {
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: `确认要删除${record.goodname}吗?`,
            onOk() {
                console.log(record);
                axios.post("http://localhost:8080/deleteUser?id=" + record.id).then(resp => {
                    if (resp.data.state === "0") {
                        message.success(resp.data.message, 1);
                        setTimeout(() => {
                            window.location.reload();
                        }, 500);
                    } else {
                        message.error(resp.data.message, 1)
                    }
                }).catch(err => {
                    console.log(err);
                    message.error("网络超时!", 1)
                })
            },
            onCancel() {
            },
        });
    }
    const columns = [
        {
            title: '物品名称',
            dataIndex: 'goodname',
            align: 'center',
        },
        {
            title: '物品积分',
            dataIndex: 'goodpoint',
            sorter: (a, b) => a.goodpoint - b.goodpoint,
        },
        {
            title: 'Action',
            key: 'action',
            width: '15%',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => { showModal(record) }}>编辑<EditTwoTone /></a>
                    <a onClick={() => { deleteUser(record) }} style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
                </Space>
            ),
        },
    ];

    const showModal = (record) => {
        seteditVisible(true);
        setEditGood(record)
        console.log("当前物品id",record);
    };
    const showModal2 = () => {
        setaddVisible(true);
       
    };

    const handleOk = async () => {
        console.log("修改的物品:",editGood);
        let params = {id:editGood.id}
        let point = editGoodPoint.current.value ||null
        let name = editGoodName.current.state.value ||null
        params.goodname = name;
        params.goodpoint = point
        params.oldName = editGood.goodname
        console.log("修改的物品",params);

        const resp = await axios.post("http://localhost:8080/editGood",params)
        console.log(resp);
        if (resp.data.state =="0") {
            message.success(resp.data.message)
            window.location.reload()
        }else{
            message.error(resp.data.message)
            window.location.reload()
        }

    };

    const handleOk2 = async() => {
        let params = {};
        let point  = newGoodPoint.current.value;
        let name = newGoodName.current.state.value;
        params.goodname = name;
        params.goodpoint = point;
        console.log("新增物品信息",params);
        const resp = await axios.post("http://localhost:8080/addGood", params)
        if (resp.data.state =="0") {
            message.success(resp.data.message)
            window.location.reload()
        }else{
            message.error(resp.data.message)
            window.location.reload()
        }
    };
    const handleCancel = () => {
        seteditVisible(false);
        editUserInfo = {}
    };

    const handleCancel2 = () => {
        setaddVisible(false);
        addUserInfo = {}
    };
    const onSearch = (value) => {
        console.log(value);
        let rs = [];
        rs = originData.filter((item, index) => {
            console.log(item);
            return item.goodname.indexOf(value) != -1
        })
        console.log(rs);
        setOriginData(rs)
        if (value == null || value == "") {
            setOriginData(goodList)
        }

    }
    const renderTableHead = () => {
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>物品管理</span>
                <Space>
                    <Search placeholder="物品名称" onSearch={onSearch} allowClear style={{ width: 200 }} />
                    <Button type="primary" onClick={showModal2}>添加物品</Button>
                </Space>
            </div>

        )
    }
    return (
        <Content style={{ minHeight: 285 }} className="animate__animated animate__fadeIn">
            <Table columns={columns} dataSource={originData} bordered title={renderTableHead}
                pagination={{
                    pageSize: 8,
                }}
            />
            <Modal
                title="编辑物品"
                visible={editvisible}
                onOk={handleOk}
                onCancel={handleCancel}
                centered={true}
            >
                <Row align="middle" style={{ marginBottom: 20 }}>
                    <Col>
                        获得积分:
                    </Col>
                    <Col>
                        <InputNumber min={0} max={100} ref={editGoodPoint} />
                    </Col>
                </Row>

                <Row align="middle">
                    <Col>
                        物品名称:
                    </Col>
                    <Col>
                        <Input maxLength={10} ref={editGoodName} />
                    </Col>
                </Row>
            </Modal>
            <Modal
                title="新增物品"
                visible={addvisible}
                onOk={handleOk2}
                onCancel={handleCancel2}
                centered={true}
            >
                <Row align="middle" style={{ marginBottom: 20 }}>
                    <Col>
                        获得积分:
                    </Col>
                    <Col>
                        <InputNumber min={0} max={100} ref={newGoodPoint} />
                    </Col>
                </Row>

                <Row align="middle">
                    <Col>
                        物品名称:
                    </Col>
                    <Col>
                        <Input maxLength={10} ref={newGoodName} />
                    </Col>
                </Row>
            </Modal>
        </Content>
    )

}
